package com.briup.jd2511.jd2511bookstore.service.impl;


import com.briup.jd2511.jd2511bookstore.annotation.MyLog;
import com.briup.jd2511.jd2511bookstore.annotation.SystemLog;
import com.briup.jd2511.jd2511bookstore.exception.ServiceException;
import com.briup.jd2511.jd2511bookstore.mapper.UserMapper;
import com.briup.jd2511.jd2511bookstore.pojo.User;
import com.briup.jd2511.jd2511bookstore.pojo.dto.UserLogin;
import com.briup.jd2511.jd2511bookstore.pojo.dto.UserPageDto;
import com.briup.jd2511.jd2511bookstore.pojo.vo.UserPageVO;
import com.briup.jd2511.jd2511bookstore.response.ResultCode;
import com.briup.jd2511.jd2511bookstore.service.UserLogService;
import com.briup.jd2511.jd2511bookstore.service.UserService;
import com.briup.jd2511.jd2511bookstore.utils.BeanCopyUtils;
import com.briup.jd2511.jd2511bookstore.utils.JwtUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

	@Resource
	private UserMapper userMapper;

	@Autowired
//	private UserLogMapper userLogMapper;
	private UserLogService userLogService;

	/**
	 * 用户登录逻辑处理
	 *
	 * @param userLogin 用户登录对象 内含用户名及密码
	 *                  后可添加验证码等数据
	 * @return user
	 */
	@Override
	public String login(UserLogin userLogin) {
		//判断用户名和密码是否存在值(参数校验)
		if (userLogin == null
				|| !StringUtils.hasText(userLogin.getUsername())
				|| !StringUtils.hasText(userLogin.getPassword())) {
			throw new ServiceException(ResultCode.PARAM_NOT_COMPLETE);
		}

		User user = userMapper.getUserByUsername(userLogin.getUsername());

		//判断用户是否存在及密码是否正确
		if (user == null || !userLogin.getPassword().equals(user.getPassword())) {
			throw new ServiceException(ResultCode.USER_LOGIN_ERROR);
		}

		//判断用户状态是否可用 用户状态(0正常，1禁用)
		if (user.getStatus() == 1) {
			throw new ServiceException(ResultCode.USER_ACCOUNT_FORBIDDEN);
		}

		// 生成jwt字符串
		Map<String,Object> map = new HashMap<>();
		map.put("id", user.getId());
		map.put("username", user.getUsername());
		map.put("avatar",user.getAvatar());
		return JwtUtil.generateJwt(map);
	}

	/**
	 * 分页多条件查询用户信息
	 *
	 * @param userPageDto 用于封装分页多条件查询用户时的条件参数
	 */
	@Override
	@MyLog
	public PageInfo<UserPageVO> getUsersPageByConditional(UserPageDto userPageDto) {
		//使用PageHelper开启分页,设置分页参数
		PageHelper.startPage(userPageDto.getPageNum(), userPageDto.getPageSize());

		//根据条件查询所有相关的用户
		List<User> userList = userMapper.getUserListByConditional(userPageDto);
		Page<User> page = (Page<User>) userList;

		//Bean拷贝
		List<UserPageVO> userPageVOS = BeanCopyUtils.copyBeanList(userList, UserPageVO.class);

		//封装在PageInfo对象中,并返回
		PageInfo<UserPageVO> pageInfo = new PageInfo<>(userPageVOS);
		//设置总条数
		pageInfo.setTotal(page.getTotal());

		return pageInfo;
	}

	@Override
//	@MyLog
	@SystemLog(businessName = "批量删除用户")
	public void deleteUsers(List<Integer> ids) {
		userMapper.deleteUsers(ids);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@SystemLog(businessName = "新增用户")
	public void addUser(User user) throws Exception {
		if (user == null) {
			throw new ServiceException(ResultCode.PARAM_NOT_COMPLETE);
		}
		// 新增用户的时候需不需要验证用户名是否已存在
		// 验证用户名, 如果已存在则抛出异常
		if (userMapper.getUserByUsername(user.getUsername()) != null) {
			throw new ServiceException(ResultCode.USER_HAS_EXISTED);
		}

		user.setRegisterTime(LocalDateTime.now());
		user.setIsVip(false);
		user.setRoleId((short)2);
		user.setGender(user.getGender()==null?"0":user.getGender());
		userMapper.insertUser(user);

//		try {
//			// 制造异常
//			// int i = 10/0;
//			if (true) {
//				throw new Exception();
//			}
//		}finally {
//			// 下面为新增代码
//			// 向UserLog表中添加一条日志
//			UserLog userLog = new UserLog();
//			userLog.setMessage("进行新增用户的操作："+user.getUsername());
//			userLog.setCreateTime(new Date());
////			userLogMapper.insert(userLog);
//			userLogService.addUserLog(userLog);
//		}

	}

	@Override
	public User getUserById(Integer id) {
		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	@SystemLog(businessName = "更新用户")
	public void updateUser(User user) {
		userMapper.updateSelectiveByPrimaryKey(user);
	}
}
